import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

import java.util.Arrays;

/**
 * 旋转字符串
 *
 * @author godfrey
 * @since 2020-10-12
 */
@DisplayName("旋转字符串")
public class JunitString extends BaseTest {

    @DisplayName("旋转字符串=>把字符串开头的m个字符移动到字符串s的尾部")
    @Nested
    class RotateString {
        @DisplayName("暴力移位法")
        @ParameterizedTest
        @CsvSource({"abcd,1", "abcdefg,3"})
        void leftRotateString(String s, int m) {
            Assertions.assertTrue(m > 0 && m < s.length());
            String s1 = s.substring(0, m);
            String s2 = s.substring(m, s.length());
            System.out.println(s2 + s1);
        }

        @DisplayName("三步反转法")
        @ParameterizedTest
        @CsvSource({"abcd,1", "abcdefg,3"})
        void leftRotateString2(String s, int m) {
            Assertions.assertTrue(m > 0 && m < s.length());
            String s1 = reverseString(s.substring(0, m));
            String s2 = reverseString(s.substring(m, s.length()));
            System.out.println(reverseString(s1 + s2));

        }

        String reverseString(String st) {
            char[] s = st.toCharArray();
            int from = 0, to = st.length() - 1;
            while (from < to) {
                char t = s[from];
                s[from++] = s[to];
                s[to--] = t;
            }
            return new String(s);
        }
    }

    @DisplayName("字符串包含=>给定一长一短的两个字符串A，B，假设A长B短，要求判断B是否包含在字符串A中")
    @Nested
    class StringContain {
        @DisplayName("逐个比较")
        @ParameterizedTest
        @CsvSource({"AEBD,AD", "ACDFE,ABF"})
        void stringContain(String a, String b) {
            boolean flag = true;
            for (int i = 0; i < b.length() - 1; ++i) {
                String s = b.substring(i, i + 1);
                if (!a.contains(s)) {
                    flag = false;
                    break;
                }
            }
            System.out.println(flag);
        }

        @DisplayName("先排序，再比较")
        @ParameterizedTest
        @CsvSource({"AEBD,AD", "ACDFE,ABF"})
        void stringContain2(String a, String b) {
            char[] ac = a.toCharArray();
            char[] bc = b.toCharArray();
            Arrays.sort(ac);
            Arrays.sort(bc);
            a = new String(ac);
            b = new String(bc);
            boolean flag = false;
            if (a.contains(b)) {
                flag = true;
            }
            System.out.println(flag);

        }
    }
}
